package com.example.controller;

import com.example.domain.Medication;
import com.example.service.MedicationService;
import com.example.utils.AjaxResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

import static com.example.utils.AjaxResult.*;


@RestController
@RequestMapping("/root")
public class MedicationController {
    @Autowired
    private MedicationService medicationService;

    /** 药品管理 */
    @RequestMapping("/medication")
    public AjaxResult medication(@RequestParam(defaultValue = "1", value = "page") Integer pageNum,
                                 @RequestParam(defaultValue = "10", value = "limit") Integer pageSize,
                                 @RequestParam(defaultValue = "" , value = "medication_name") String usr
    ){
        HashMap<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);

        if (usr == null || usr.equals("")) {
            map.put("usr","");
            List<Medication> medications = medicationService.listAll(map);
            System.out.println(medications.toString());
            PageInfo<Medication> page = new PageInfo<>(medications);
            return successData(page.getTotal(), medications);
        }
        map.put("usr",usr);
        List<Medication> medications = medicationService.listAll(map);
        PageInfo<Medication> page = new PageInfo<>(medications);
        return successData(page.getTotal(), medications);
    }


    /** 药品添加 */
    @RequestMapping("/addMedication")
    public AjaxResult addMedication(Medication medication){
        System.out.println(medication);
        int insert = medicationService.insert(medication);
        if (1 == insert){
            return success("添加成功");
        }
        return error("添加失败");
    }

    /** 药品修改 */
    @RequestMapping("/modifyMedication")
    public AjaxResult modifyMedication(Medication medication){

        int update = medicationService.update(medication);

        if (1 == update){
            return success("修改成功");
        }
        return error("修改失败");
    }
}
